"""
性能管理模块信号处理
"""
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from .models import PerformanceMonitor, SystemResource


@receiver(post_save, sender=SystemResource)
def check_performance_alerts(sender, instance, created, **kwargs):
    """检查性能告警"""
    if not created:
        issues = instance.check_health()
        if issues:
            # 创建性能监控记录
            PerformanceMonitor.objects.create(
                metric_type=PerformanceMonitor.MetricType.SYSTEM_PERFORMANCE,
                component=PerformanceMonitor.Component.APPLICATION,
                metric_value=100 if not instance.is_healthy else 0,
                metadata={
                    'server_name': instance.server_name,
                    'issues': issues,
                    'cpu_usage': float(instance.cpu_usage or 0),
                    'memory_usage': float(instance.memory_usage or 0),
                    'disk_usage': float(instance.disk_usage or 0)
                },
                status='critical' if not instance.is_healthy else 'normal'
            )